<template>
  <div class="dashboard-container">
    <!-- 页面标题 -->
    <div class="dashboard-header">
      <div class="header-content">
        <div class="header-icon">
          <BarChart3 :size="28" />
        </div>
        <div class="header-text">
          <h1 class="header-title">系统仪表盘</h1>
          <p class="header-subtitle">实时监控系统运行状态和数据统计</p>
        </div>
      </div>
      <div class="header-actions">
        <a-button @click="refreshData" :loading="loading" type="primary">
          <template #icon>
            <RefreshCw :size="16" />
          </template>
          刷新数据
        </a-button>
      </div>
    </div>

    <!-- 统计卡片区域 -->
    <div class="stats-cards">
      <div class="card-grid">
        <div class="stat-card">
          <div class="card-content">
            <div class="card-icon users">
              <Users :size="24" />
            </div>
            <div class="card-info">
              <div class="card-value">{{ statisticsData?.cardData?.totalUsers || 0 }}</div>
              <div class="card-label">总用户数</div>
            </div>
          </div>
        </div>

        <div class="stat-card">
          <div class="card-content">
            <div class="card-icon chat-rooms">
              <MessageCircle :size="24" />
            </div>
            <div class="card-info">
              <div class="card-value">{{ statisticsData?.cardData?.totalChatRooms || 0 }}</div>
              <div class="card-label">聊天室数量</div>
            </div>
          </div>
        </div>

        <div class="stat-card">
          <div class="card-content">
            <div class="card-icon ai-roles">
              <Bot :size="24" />
            </div>
            <div class="card-info">
              <div class="card-value">{{ statisticsData?.cardData?.totalAiRoles || 0 }}</div>
              <div class="card-label">AI角色数量</div>
            </div>
          </div>
        </div>

        <div class="stat-card">
          <div class="card-content">
            <div class="card-icon voices">
              <Volume2 :size="24" />
            </div>
            <div class="card-info">
              <div class="card-value">{{ statisticsData?.cardData?.totalVoices || 0 }}</div>
              <div class="card-label">音色数量</div>
            </div>
          </div>
        </div>

        <div class="stat-card">
          <div class="card-content">
            <div class="card-icon knowledge">
              <Database :size="24" />
            </div>
            <div class="card-info">
              <div class="card-value">{{ statisticsData?.cardData?.totalKnowledgeBases || 0 }}</div>
              <div class="card-label">知识库数量</div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 图表区域 -->
    <div class="charts-section">
      <!-- 仪表盘区域 -->
      <div class="gauge-section">
        <div class="gauge-grid">
          <!-- 存储使用率仪表盘 -->
          <div class="gauge-card">
            <div class="gauge-header">
              <h3 class="gauge-title">存储使用率</h3>
              <div class="gauge-subtitle">当前系统存储空间使用情况</div>
            </div>
            <div class="gauge-content">
              <v-chart
                class="gauge-chart"
                :option="storageGaugeOption"
                :loading="loading"
                autoresize
              />
            </div>
          </div>

          <!-- 系统负载仪表盘 -->
          <div class="gauge-card">
            <div class="gauge-header">
              <h3 class="gauge-title">系统负载</h3>
              <div class="gauge-subtitle">当前系统CPU负载情况</div>
            </div>
            <div class="gauge-content">
              <v-chart
                class="gauge-chart"
                :option="systemLoadGaugeOption"
                :loading="loading"
                autoresize
              />
            </div>
          </div>
        </div>
      </div>

      <div class="charts-grid">
        <!-- 聊天室消息趋势图 -->
        <div class="chart-card">
          <div class="chart-header">
            <h3 class="chart-title">聊天室消息趋势</h3>
            <div class="chart-subtitle">最近7天聊天室消息数量变化</div>
          </div>
          <div class="chart-content">
            <v-chart
              class="chart"
              :option="chatRoomChartOption"
              :loading="loading"
              autoresize
            />
          </div>
        </div>

        <!-- 对话消息趋势图 -->
        <div class="chart-card">
          <div class="chart-header">
            <h3 class="chart-title">对话消息趋势</h3>
            <div class="chart-subtitle">最近7天对话消息数量变化</div>
          </div>
          <div class="chart-content">
            <v-chart
              class="chart"
              :option="conversationChartOption"
              :loading="loading"
              autoresize
            />
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { message } from 'ant-design-vue'
import {
  BarChart3,
  RefreshCw,
  Users,
  MessageCircle,
  Bot,
  Volume2,
  Database
} from 'lucide-vue-next'
import VChart from 'vue-echarts'
import { use } from 'echarts/core'
import {
  CanvasRenderer
} from 'echarts/renderers'
import {
  LineChart,
  GaugeChart
} from 'echarts/charts'
import {
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent
} from 'echarts/components'
import { Codewin } from '@/api/generated/Codewin'
import { useAuthStore } from '@/stores/modules/auth'

// 注册 ECharts 组件
use([
  CanvasRenderer,
  LineChart,
  GaugeChart,
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent
])

// 接口类型定义
interface StatisticsData {
  cardData: {
    totalUsers: number
    totalChatRooms: number
    totalAiRoles: number
    totalVoices: number
    totalKnowledgeBases: number
    storageUsageRate: number
    systemLoad: number
  }
  chartData: {
    chatRoomMessageTrend: Array<{
      date: string
      count: number
    }>
    conversationMessageTrend: Array<{
      date: string
      count: number
    }>
  }
}

// 响应式数据
const loading = ref(false)
const statisticsData = ref<StatisticsData | null>(null)

// Store
const authStore = useAuthStore()

// API实例
const api = new Codewin({
  baseURL: import.meta.env.VITE_API_BASE_URL || '/api',
  securityWorker: () => ({
    headers: {
      Authorization: `Bearer ${authStore.token}`
    }
  })
})

// 创建带认证头的配置
const createAuthHeaders = () => {
  const token = authStore.token
  return token ? { Authorization: `Bearer ${token}` } : {}
}

// 格式化百分比
const formatPercentage = (value?: number) => {
  if (value === undefined || value === null) return '0%'
  return `${value.toFixed(1)}%`
}

// 格式化系统负载
const formatSystemLoad = (value?: number) => {
  if (value === undefined || value === null) return '0.0'
  return value.toFixed(2)
}

// 聊天室消息趋势图配置
const chatRoomChartOption = computed(() => ({
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'cross'
    }
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    containLabel: true
  },
  xAxis: {
    type: 'category',
    boundaryGap: false,
    data: statisticsData.value?.chartData?.chatRoomMessageTrend?.map(item => item.date) || []
  },
  yAxis: {
    type: 'value'
  },
  series: [
    {
      name: '聊天室消息数',
      type: 'line',
      smooth: true,
      symbol: 'circle',
      symbolSize: 6,
      lineStyle: {
        color: '#667eea',
        width: 3
      },
      itemStyle: {
        color: '#667eea'
      },
      areaStyle: {
        color: {
          type: 'linear',
          x: 0,
          y: 0,
          x2: 0,
          y2: 1,
          colorStops: [
            {
              offset: 0,
              color: 'rgba(102, 126, 234, 0.3)'
            },
            {
              offset: 1,
              color: 'rgba(102, 126, 234, 0.05)'
            }
          ]
        }
      },
      data: statisticsData.value?.chartData?.chatRoomMessageTrend?.map(item => item.count) || []
    }
  ]
}))

// 存储使用率仪表盘配置
const storageGaugeOption = computed(() => ({
  tooltip: {
    formatter: '{a} <br/>{b} : {c}%'
  },
  series: [
    {
      name: '存储使用率',
      type: 'gauge',
      center: ['50%', '55%'],
      startAngle: 200,
      endAngle: -20,
      min: 0,
      max: 100,
      splitNumber: 10,
      itemStyle: {
        color: '#58D9F9',
        shadowColor: 'rgba(0,138,255,0.45)',
        shadowBlur: 10,
        shadowOffsetX: 2,
        shadowOffsetY: 2
      },
      progress: {
        show: true,
        roundCap: true,
        width: 18
      },
      pointer: {
        icon: 'path://M2090.36389,615.30999 L2090.36389,615.30999 C2091.48372,615.30999 2092.40383,616.194028 2092.44859,617.312956 L2096.90698,728.755929 C2097.05155,732.369577 2094.2393,735.416212 2090.62566,735.56078 C2090.53845,735.564269 2090.45117,735.566014 2090.36389,735.566014 L2090.36389,735.566014 C2086.74736,735.566014 2083.81557,732.63423 2083.81557,729.017692 C2083.81557,728.930412 2083.81732,728.84314 2083.82081,728.755929 L2088.2792,617.312956 C2088.32396,616.194028 2089.24407,615.30999 2090.36389,615.30999 Z',
        length: '75%',
        width: 16,
        offsetCenter: [0, '5%']
      },
      axisLine: {
        roundCap: true,
        lineStyle: {
          width: 18
        }
      },
      axisTick: {
        splitNumber: 2,
        lineStyle: {
          width: 2,
          color: '#999'
        }
      },
      splitLine: {
        length: 12,
        lineStyle: {
          width: 3,
          color: '#999'
        }
      },
      axisLabel: {
        distance: 35,
        color: '#999',
        fontSize: 16
      },
      title: {
        show: false
      },
      detail: {
        backgroundColor: '#fff',
        width: '30%',
        lineHeight: 50,
        height: 50,
        borderRadius: 8,
        offsetCenter: [0, '40%'],
        valueAnimation: true,
        formatter: function (value: number) {
          return '{value|' + value.toFixed(1) + '}{unit|%}'
        },
        rich: {
          value: {
            fontSize: 32,
            fontWeight: 'bolder',
            color: '#777'
          },
          unit: {
            fontSize: 14,
            color: '#999',
            padding: [0, 0, -15, 8]
          }
        }
      },
      data: [
        {
          value: statisticsData.value?.cardData?.storageUsageRate || 0,
          name: '存储使用率'
        }
      ]
    }
  ]
}))

// 系统负载仪表盘配置
const systemLoadGaugeOption = computed(() => ({
  tooltip: {
    formatter: '{a} <br/>{b} : {c}%'
  },
  series: [
    {
      name: '系统负载',
      type: 'gauge',
      center: ['50%', '55%'],
      startAngle: 200,
      endAngle: -20,
      min: 0,
      max: 100,
      splitNumber: 10,
      itemStyle: {
        color: '#FFAB91',
        shadowColor: 'rgba(255,171,145,0.45)',
        shadowBlur: 10,
        shadowOffsetX: 2,
        shadowOffsetY: 2
      },
      progress: {
        show: true,
        roundCap: true,
        width: 18
      },
      pointer: {
        icon: 'path://M2090.36389,615.30999 L2090.36389,615.30999 C2091.48372,615.30999 2092.40383,616.194028 2092.44859,617.312956 L2096.90698,728.755929 C2097.05155,732.369577 2094.2393,735.416212 2090.62566,735.56078 C2090.53845,735.564269 2090.45117,735.566014 2090.36389,735.566014 L2090.36389,735.566014 C2086.74736,735.566014 2083.81557,732.63423 2083.81557,729.017692 C2083.81557,728.930412 2083.81732,728.84314 2083.82081,728.755929 L2088.2792,617.312956 C2088.32396,616.194028 2089.24407,615.30999 2090.36389,615.30999 Z',
        length: '75%',
        width: 16,
        offsetCenter: [0, '5%']
      },
      axisLine: {
        roundCap: true,
        lineStyle: {
          width: 18
        }
      },
      axisTick: {
        splitNumber: 2,
        lineStyle: {
          width: 2,
          color: '#999'
        }
      },
      splitLine: {
        length: 12,
        lineStyle: {
          width: 3,
          color: '#999'
        }
      },
      axisLabel: {
        distance: 35,
        color: '#999',
        fontSize: 16
      },
      title: {
        show: false
      },
      detail: {
        backgroundColor: '#fff',
        width: '30%',
        lineHeight: 50,
        height: 50,
        borderRadius: 8,
        offsetCenter: [0, '40%'],
        valueAnimation: true,
        formatter: function (value: number) {
          return '{value|' + value.toFixed(1) + '}{unit|%}'
        },
        rich: {
          value: {
            fontSize: 32,
            fontWeight: 'bolder',
            color: '#777'
          },
          unit: {
            fontSize: 14,
            color: '#999',
            padding: [0, 0, -15, 8]
          }
        }
      },
      data: [
        {
          value: statisticsData.value?.cardData?.systemLoad || 0,
          name: '系统负载'
        }
      ]
    }
  ]
}))

// 对话消息趋势图配置
const conversationChartOption = computed(() => ({
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'cross'
    }
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    containLabel: true
  },
  xAxis: {
    type: 'category',
    boundaryGap: false,
    data: statisticsData.value?.chartData?.conversationMessageTrend?.map(item => item.date) || []
  },
  yAxis: {
    type: 'value'
  },
  series: [
    {
      name: '对话消息数',
      type: 'line',
      smooth: true,
      symbol: 'circle',
      symbolSize: 6,
      lineStyle: {
        color: '#f093fb',
        width: 3
      },
      itemStyle: {
        color: '#f093fb'
      },
      areaStyle: {
        color: {
          type: 'linear',
          x: 0,
          y: 0,
          x2: 0,
          y2: 1,
          colorStops: [
            {
              offset: 0,
              color: 'rgba(240, 147, 251, 0.3)'
            },
            {
              offset: 1,
              color: 'rgba(240, 147, 251, 0.05)'
            }
          ]
        }
      },
      data: statisticsData.value?.chartData?.conversationMessageTrend?.map(item => item.count) || []
    }
  ]
}))

// 获取统计数据
const fetchStatisticsData = async () => {
  try {
    loading.value = true
    const response = await api.getStatisticsOverview({
      headers: createAuthHeaders()
    })

    if (response.data?.code === 0 && response.data.data) {
      statisticsData.value = response.data.data
    } else {
      message.error('获取统计数据失败')
    }
  } catch (error) {
    console.error('获取统计数据失败:', error)
    message.error('获取统计数据失败')
  } finally {
    loading.value = false
  }
}

// 刷新数据
const refreshData = () => {
  fetchStatisticsData()
}

// 组件挂载时获取数据
onMounted(() => {
  fetchStatisticsData()
})
</script>

<style scoped>
.dashboard-container {
  padding: 0;
  background: #f8fafc;
  min-height: max(100vh, 1000px);
}

/* 页面标题 */
.dashboard-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 32px;
  padding: 24px 32px;
  background: white;
  border-radius: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
}

.header-content {
  display: flex;
  align-items: center;
  gap: 16px;
}

.header-icon {
  width: 56px;
  height: 56px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  box-shadow: 0 8px 24px rgba(102, 126, 234, 0.3);
}

.header-text {
  flex: 1;
}

.header-title {
  margin: 0;
  font-size: 28px;
  font-weight: 700;
  color: #1a202c;
  line-height: 1.2;
}

.header-subtitle {
  margin: 4px 0 0 0;
  font-size: 16px;
  color: #64748b;
  line-height: 1.4;
}

.header-actions {
  display: flex;
  gap: 12px;
}

/* 统计卡片区域 */
.stats-cards {
  margin-bottom: 32px;
}

.card-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
  gap: 24px;
  margin-bottom: 32px;
}

.stat-card {
  background: white;
  border-radius: 16px;
  padding: 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
  border: 1px solid rgba(0, 0, 0, 0.02);
  transition: all 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.12);
}

.card-content {
  display: flex;
  align-items: center;
  gap: 16px;
}

.card-icon {
  width: 48px;
  height: 48px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  flex-shrink: 0;
}

.card-icon.users {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.card-icon.chat-rooms {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}

.card-icon.ai-roles {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
}

.card-icon.voices {
  background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
}

.card-icon.knowledge {
  background: linear-gradient(135deg, #fa709a 0%, #fee140 100%);
}

.card-icon.storage {
  background: linear-gradient(135deg, #a8edea 0%, #fed6e3 100%);
}

.card-icon.system-load {
  background: linear-gradient(135deg, #ffecd2 0%, #fcb69f 100%);
}

.card-info {
  flex: 1;
}

.card-value {
  font-size: 32px;
  font-weight: 700;
  color: #1a202c;
  line-height: 1;
  margin-bottom: 4px;
}

.card-label {
  font-size: 14px;
  color: #64748b;
  font-weight: 500;
}

/* 图表区域 */
.charts-section {
  margin-top: 32px;
}

/* 仪表盘区域 */
.gauge-section {
  margin-bottom: 32px;
}

.gauge-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 24px;
}

.gauge-card {
  background: white;
  border-radius: 16px;
  padding: 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
  border: 1px solid rgba(0, 0, 0, 0.02);
  transition: all 0.3s ease;
}

.gauge-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.12);
}

.gauge-header {
  margin-bottom: 16px;
  text-align: center;
}

.gauge-title {
  margin: 0 0 8px 0;
  font-size: 20px;
  font-weight: 600;
  color: #1a202c;
}

.gauge-subtitle {
  font-size: 14px;
  color: #64748b;
}

.gauge-content {
  height: 350px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.gauge-chart {
  width: 100%;
  height: 100%;
}

.charts-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(500px, 1fr));
  gap: 24px;
}

.chart-card {
  background: white;
  border-radius: 16px;
  padding: 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
  border: 1px solid rgba(0, 0, 0, 0.02);
}

.chart-header {
  margin-bottom: 24px;
}

.chart-title {
  margin: 0 0 8px 0;
  font-size: 20px;
  font-weight: 600;
  color: #1a202c;
}

.chart-subtitle {
  font-size: 14px;
  color: #64748b;
}

.chart-content {
  height: 300px;
}

.chart {
  width: 100%;
  height: 100%;
}

/* 响应式设计 */
@media (max-width: 1024px) {
  .card-grid {
    grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
    gap: 16px;
  }

  .gauge-grid {
    grid-template-columns: 1fr;
    gap: 16px;
  }

  .charts-grid {
    grid-template-columns: 1fr;
    gap: 16px;
  }
}

@media (max-width: 768px) {
  .dashboard-header {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }

  .header-content {
    justify-content: center;
  }

  .header-actions {
    justify-content: center;
  }

  .card-grid {
    grid-template-columns: 1fr;
  }

  .gauge-grid {
    grid-template-columns: 1fr;
  }

  .gauge-content {
    height: 300px;
  }

  .chart-content {
    height: 250px;
  }
}
</style>
